# coding=utf-8
# !/usr/bin/python
import os

import cv2 as cv
import numpy as np
import requests as req
from util.cnf_utils import MyCnf
import util.common_utils as utils


class MyOpencv:

    def __init__(self):
        self._tmp_path = MyCnf('/cnf/my_config.cnf').get_value('bamboo', 'tmp_path')

    def removeWaterMark(self, url):
        # 从url下载图片到本地
        __img_path = self.__download(url)
        # 去除水印
        if __img_path is None:
            print('图片下载失败：%s' % url)
            return None
        return self.__removeWaterMark(__img_path)

    def __download(self, url):
        # 判断文件夹是否存在
        utils.createFile(self._tmp_path)
        uid = utils.getuid()
        file = uid + '.png'
        result = req.get(url)
        if result.status_code == 200:
            with open(file, 'wb') as f:
                f.write(result.content)
                return self._tmp_path + '/' + file
        return None

    def __removeWaterMark(self, img_path):
        # 提取感兴趣区域ROI
        img = cv.imread(img_path)
        img_hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)

        # 设定白色HSV范围
        lower = np.array([100, 43, 46])
        upper = np.array([111, 200, 235])
        # lower = np.array([35, 43, 46])
        # upper = np.array([124, 255, 255])

        # 创建水印蒙层
        kernel = np.ones((3, 3), np.uint8)
        mask = cv.inRange(img_hsv, lower, upper)
        # 对水印蒙层进行膨胀操作
        dilate = cv.dilate(mask, kernel, iterations=3)
        res_img = cv.inpaint(img, dilate, 1, flags=cv.INPAINT_TELEA)
        # 双边滤波
        res_img = cv.bilateralFilter(res_img, 5, 280, 50)

        # 高1:高2 宽1:宽2
        img = res_img

        # 获取原文件名和后缀
        old_name = img_path[img_path.rindex('/') + 1:]
        suffix = old_name[old_name.rindex('.'): len(old_name)]
        filename = utils.getuid() + '.' + suffix
        cv.imwrite(filename, img)
        # 删除原图
        os.remove(img_path)
        return self._tmp_path + '/' + filename


if __name__ == '__main__':
    myOpencv = MyOpencv()
    res = myOpencv.removeWaterMark('https://ke-image.ljcdn.com/hdic-frame/standard_613b7953-3bde-4131-905c-cb9a700e0050.png.533x400.jpg?from=ke.com')
    print(res)
